import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import {Tabs, message, Affix, Icon} from 'antd'
const TabPane = Tabs.TabPane;
import Skeleton from 'components/skeleton'
import invoiceBagApproveService from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve.service'
import InvoiceList from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve-detail/invoice-list'
import ExpenseList from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve-detail/expense-list'
import ReportList from 'containers/financial-management/invoice-bag-approve/invoice-bag-approve-detail/report-list'
import 'styles/financial-management/innvoice-bag-approve/invoice-bag-approve-detail.scss'
import moment from "moment";
import ApproveBar from 'components/template/approve-bar'
import menuRoute from "routes/menuRoute";
import expenseService from "containers/my-account/expense.service";

class ApprovedInvoiceBagDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabs: [
        {key: 'invoice', name: messages('financial-management.key651')/*发票*/, component: InvoiceList},
        {key: 'expense', name: messages('financial-management.key652')/*费用*/, component: ExpenseList},
        {key: 'report', name: messages('financial-management.key160')/*报销单*/, component: ReportList},
      ],
      nowTab: 'invoice',
      baseInfo: {},
      invoiceList: {
        withReceipt: [],
        freeReceipt: [],
        financeReceipts: [],
        financeReceiptStatistics: null,
        withReceiptStatistics: null,
        freeReceiptStatistics: null
      },
      loading: false,
      invoiceLoading: false,
      financeInvoiceLoading: false,
      checking: false,
      readOnly: false,
      approved: false,
      autoAuditing: false,
      hasAutoAudit: false,
      showCheckInvoiceFlag: false,
      showOCRFlag: false
    };
    this.listPage = menuRoute.getRouteItem('invoice-bag-approve')
  }

  componentDidMount() {
    this.setState({ loading: true });
    let bagId = this.props.params.id;
    const { company, user, userPermissionAllMenus } = this.props;
    let permission = userPermissionAllMenus
      .find(dto => dto.key === 'invoice-bag-approve' );
    permission && this.setState({ readOnly: permission.operationType === 'R' });
    const { location } = this.props;
    this.setState({ approved: location.query.tab === 'approved' });
    invoiceBagApproveService.canAutoAudit(company.companyOID).then(res => {
      this.setState({ hasAutoAudit: res.data })
    });
    invoiceBagApproveService.getBagDetail(bagId).then(res => {
      this.setState({
        baseInfo: res.data,
        loading: false
      });
    });
    expenseService.getTitleList(user.userOID).then(res => {
      this.setState({
        showCheckInvoiceFlag: res.data.showCheckInvoiceFlag,
        showOCRFlag: res.data.showOCRFlag
      });
    });
    this.getInvoiceList();
  }

  getInvoiceList = () => {
    let bagId = this.props.params.id;
    this.setState({ invoiceLoading: true });
    invoiceBagApproveService.getInvoiceListByBagId(bagId).then(res => {
      res.data.financeReceipts.forEach(this.mapFinanceInvoice);
      this.setState({
        invoiceLoading: false,
        invoiceList: res.data
      })
    }).catch(() => {
      this.setState({ invoiceLoading: false });
    })
  };

  mapFinanceInvoice = invoice => {
    invoice.isFinance = true;
    if(!invoice.type)
      invoice.type = messages('financial-management.key775')/*无法识别*/;
    return invoice;
  };

  handleClickMore = type => {
    if(type === 'check-invoice') {
      this.batchVerify();
    }
  };

  batchVerify = () => {
    const { invoiceList } = this.state;
    let needVerify = invoiceList.withReceipt
      .concat(invoiceList.financeReceipts)
      .concat(invoiceList.freeReceipt)
      .filter(invoice => invoice.checkResult !== 'R_0000'
        && !invoice.alipayOrWeChat
        && ["01", "03", "04", "10", "11", "14"].indexOf(invoice.invoiceTypeNo) > -1);
    if(needVerify.length === 0) {
      message.info(messages('financial-management.key744')/*没有需要查验的发票*/)
    } else {
      this.setState({ checking: true });
      invoiceBagApproveService.batchVerify(needVerify).then(res => {
        let result = res.data;
        let messageType = result.failedCount === 0 ? 'success' : 'error';
        message[messageType](messages('financial-management.key745',{
          arg1: result.successCount,
          arg2: result.failedCount
        })/*查验完成，成功{arg1}张，失败{arg2}张*/);
        this.setState({ checking: false });
        this.getInvoiceList();
      });
    }
  };

  handleApprove = (reason = '', service) => {
    const { id } = this.props.params;
    this.setState({ checking: true });
    invoiceBagApproveService[service](id, reason).then(res => {
      let { failReason, successNum, failNum } = res.data;
      if(failNum === 0) {
        this.setState({ approved: true, checking: false });
        message.success(messages('common.operate.success')/*操作成功*/);
        this.goBack();
      } else {
        let firstError = failReason[Object.keys(failReason)[0]];
        message.info(messages('financial-management.key746', {
            arg1: successNum,
            arg2: failNum,
            arg3: firstError
          })/*操作成功{arg1}条，失败{arg2}条，失败原因为：{arg3}*/);
        this.setState({ checking: false });
      }
    }).catch(() => {
      this.setState({ checking: false });
    })
  };

  goBack = () => {
    const { location } = this.props;
    this.context.router.push(this.listPage.url + `?tab=${location.query.tab}`)
  };

  getMoreButtons = () => {
    const { invoiceList, showCheckInvoiceFlag } = this.state;
    return showCheckInvoiceFlag && invoiceList.withReceipt
      .concat(invoiceList.financeReceipts)
      .concat(invoiceList.freeReceipt)
      .filter(invoice => invoice.checkResult !== 'R_0000'
        && !invoice.alipayOrWeChat
        && ["01", "03", "04", "10", "11", "14"].indexOf(invoice.invoiceTypeNo) > -1)
      .length > 0 ?
      ['check-invoice'] : [];
  };

  autoAudit = () => {
    let bagId = this.props.params.id;
    this.setState({ autoAuditing: true });
    invoiceBagApproveService.autoAudit(bagId).then(res => {
      this.setState({ autoAuditing: false });
      if(res.data.auto) {
        message.success(messages("common.operate.success")/*操作成功*/);
      } else {
        message.error(res.data.content);
      }
    }).catch(() => {
      this.setState({ autoAuditing: false })
    })
  };

  render() {
    const {
      tabs, nowTab, loading, baseInfo, invoiceList, invoiceLoading,
      checking, readOnly, approved, autoAuditing, hasAutoAudit,
      showCheckInvoiceFlag, showOCRFlag
    } = this.state;
    const { id } = this.props.params;
    const { location } = this.props;
    return (
      <div className="invoice-bag-approve-detail">
        <div className="applicant-info">
          <Skeleton loading={loading} title={false} paragraph={2}>
            <h3>
              {baseInfo.fullName}
              <span>
                {messages('financial-management.key130')/*工号*/}: {baseInfo.employeeId}
                <span className="ant-divider"/>
                {messages('financial-management.key448')/*部门*/}:
                {
                  this.checkFunctionProfiles('department.full.path.disabled', [true]) ?
                    baseInfo.departmentName :
                    baseInfo.departmentPath
                }
                <span className="ant-divider"/>
                {messages('financial-management.key128')/*法人实体*/}: {baseInfo.legalEntityName}
                <span className="ant-divider"/>
              </span>
            </h3>
            <span style={{ marginLeft: 0 }}>
              {baseInfo.expenseReportBagCode}&nbsp;&nbsp;&nbsp;&nbsp;
              {messages('financial-management.key479')/*提交日期*/}:
              {moment(baseInfo.lastSubmittedDate).local().format('YYYY-MM-DD')}
            </span>
          </Skeleton>
        </div>
        <div className="divider"/>
        <div className="tabs-content">
          <div className="tabs-info">
            <Tabs onChange={key => this.setState({ nowTab: key })} type="card">
              {tabs.map(tab => <TabPane tab={tab.name} key={tab.key}/>)}
            </Tabs>
          </div>
          {baseInfo.userOID && React.createElement(tabs.find(tab => tab.key === nowTab).component,
            {
              invoiceBagId: id,
              baseInfo,
              invoiceList,
              invoiceLoading,
              readOnly,
              approved,
              onRefreshInvoice: this.getInvoiceList,
              showCheckInvoiceFlag,
              showOCRFlag
            },
            null)}
        </div>

        {approved ? (
          <Affix offsetBottom={0} className="bottom-bar bottom-bar-approve bottom-bar-back">
            <a className="back-btn" onClick={this.goBack}>
              <Icon type="rollback" />{messages("common.back")/*返回*/}</a>
          </Affix>
        ) : (
          <Affix offsetBottom={0} className="bottom-bar bottom-bar-approve">
            <ApproveBar
              buttons={['pass', 'reject']}
              customButtons={hasAutoAudit ? [{
                text: messages('financial-management.key776')/*自动审核*/,
                onClick: this.autoAudit,
                type: 'primary',
                loading: autoAuditing
              }] : []}
              btnShowMode="all"
              backUrl={this.listPage.url + `?tab=${location.query.tab}`}
              moreButtons={this.getMoreButtons()}
              handleApprovePass={reason => this.handleApprove(reason, 'batchPass')}
              handleApproveReject={reason => this.handleApprove(reason, 'batchReject')}
              handleClickMore={this.handleClickMore}
              allLoading={checking}
            />
          </Affix>
        )}

      </div>
    )
  }
}

ApprovedInvoiceBagDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    userPermissionAllMenus: state.login.userPermissionAllMenus,
    company: state.login.company
  }
}

export default connect(mapStateToProps)(ApprovedInvoiceBagDetail)
